<?php

namespace app\admin\controller\training\published;

use app\admin\service\UserService;
use app\BaseController;
use app\model\FollowUserModel;
use app\model\not_del\TrainingTaskUserDelLogModel;
use app\model\training\TrainingTaskDepartmentModel;
use app\model\training\TrainingTaskModel;
use app\model\training\TrainingTaskRatingScaleModel;
use app\model\training\TrainingTaskUserModel;
use app\model\not_del\UserModel as NotDelUserModel;
use app\model\training\TrainingTaskUserResultModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\App;

class Index extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 设置查看权限
     * @return bool|string
     */
    public function callableView(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|Id' => 'require',
                'callable_view|查看状态' => 'require'
            ]);
            $TrainingTaskUserResultModel = new TrainingTaskUserResultModel();
            $info = $TrainingTaskUserResultModel->find($param['id']);
            $info->save([
                'callable_view' => $param['callable_view']
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 加入关注
     * @return bool|string
     */
    public function addFollow(): bool|string
    {
        $TrainingTaskUserResultModel = new TrainingTaskUserResultModel();
        $TrainingTaskUserResultModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require|integer|max:11',
                'level|关注等级' => 'require',
                'reason|关注原因' => 'require',
            ]);
            $info = $TrainingTaskUserResultModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $FollowUserModel = new FollowUserModel();
            $FollowUserModel->insert([
                'unit_id' => $this->userData['unit_id'],
                'operator_uid' => $this->userData['id'],
                'uid' => $info['uid'],
                'level' => $param['level'],
                'reason' => $param['reason'],
                'channel' => 12,
                'channel_id' => $param['id'],
                'time' => time()
            ]);
            $info->save([
                'is_follow' => 1
            ]);
            $TrainingTaskUserResultModel->commit();
            return success();
        } catch (\Exception $e) {
            $TrainingTaskUserResultModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 查询任务状态
     * @return bool|string
     */
    public function taskStatus(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
            $TrainingTaskModel = new TrainingTaskModel();
            if (is_array($param['id'])) {
                $status = $TrainingTaskModel->where('id', 'in', $param['id'])->distinct(true)->column('status');
            } else {
                $status = $TrainingTaskModel->where('id', '=', $param['id'])->distinct(true)->column('status');
            }
            return success($status);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 发布人选择器
     * @return bool|string
     */
    public function publisherSelector(): bool|string
    {
        try {
            $TrainingTaskModel = new TrainingTaskModel();
            $uid = $TrainingTaskModel->where('unit_id', '=', $this->userData['unit_id'])->column('uid');
            $UserModel = new NotDelUserModel();
            $data = $UserModel->where('id', 'in', $uid)->field('id,name')->select();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 已发布培训列表
     * @return bool|string
     */
    public function index(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'pageSize|每页显示数量' => 'require',
            ]);
            $where = [];
            if (!empty($param['name'])){
                $where[] = ['name','like','%'.$param['name'].'%'];
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['type_id'])){
                $where[] = ['type_id','=',$param['type_id']];
            }
            if (!empty($param['status'])){
                $where[] = ['status','=',$param['status']];
            }
            if (isset($param['review']) && strlen($param['review']) > 0){
                $where[] = ['review','=',$param['review']];
            }
            if (!empty($param['uid'])){
                $where[] = ['uid','=',$param['uid']];
            }
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $TrainingTaskModel = new TrainingTaskModel();
            $query = $TrainingTaskModel->where($where);
            $data = $query->with([
                'user' => function ($query) {
                    $query->with(['roleName']);
                },
                'typeName',
                'textbook',
                'TrainingTaskRatingScaleFront' => function ($query) {
                    $query->with(['ratingScale']);
                },
                'TrainingTaskRatingScaleAfter' => function ($query) {
                    $query->with(['ratingScale']);
                }
            ])->paginate($param['pageSize'])->toArray();
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 删除发布记录
     * @return bool|string
     */
    public function del(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
            $TrainingTaskModel = new TrainingTaskModel();
            $status = $TrainingTaskModel->where('id','in',$param['id'])->distinct(true)->column('status');
            if (in_array(2,$status) || in_array(3,$status) || in_array(4,$status)) throw new \Exception('未开始或已结束的活动才可删除！');
            $TrainingTaskModel->where('id','in',$param['id'])->update([
                'is_del' => 1,
                'del_time' => time()
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 发布信息（用于编辑）
     * @return bool|string
     */
    public function info(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
            $TrainingTaskModel = new TrainingTaskModel();
            $info = $TrainingTaskModel->with([
                'TrainingTaskDepartment',
                'TrainingTaskRatingScaleFront' => function ($query) {
                    $query->with(['ratingScale']);
                },
                'TrainingTaskRatingScaleAfter' => function ($query) {
                    $query->with(['ratingScale']);
                }
            ])->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            if (!empty($info['TrainingTaskDepartment'])){
                $UserService = new UserService($this->app);
                $allDepartment = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
                foreach ($info['TrainingTaskDepartment'] as &$department){
                    $department['name'] = $allDepartment[$department['department_id']]['all_name']??'--';
                }
            }
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 编辑发布记录
     * @return bool|string
     */
    public function update2(): bool|string
    {
        $TrainingTaskModel = new TrainingTaskModel();
        $TrainingTaskModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'name|讲座名称' => 'require',
                'type_id|讲座类型' => 'require',
                'start_time|举行开始时间' => 'require',
                'end_time|举行结束时间' => 'require',
                'review|报告是否需要审核' => 'require',
                'address|举行地址' => 'require',
                'lecturer_id|讲师' => 'require',
                'textbook_id|教材' => 'require',
                'is_download|是否允许下载' => 'require',
                'task_type|附带任务类型' => 'require',
                'result_read_auth|结果查看权限' => 'require',
                'introduce|简介' => 'require',
                'department|参与部门' => 'require'
            ]);
            $info = $TrainingTaskModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            unset($param['id']);
            if (!empty($param['department'])) {
                $departmentData = [];
                foreach ($param['department'] as $department_id) {
                    $departmentData[] = [
                        'unit_id' => $this->userData['unit_id'],
                        'department_id' => $department_id,
                        'time' => time()
                    ];
                }
                unset($param['department']);
            }
            $ratingScaleData = [];
            switch ($param['task_type']) {
                case 1:
                    if (!empty($param['rating_scale_front'])) {
                        foreach ($param['rating_scale_front'] as $rating_scale_id) {
                            $ratingScaleData[] = [
                                'rating_scale_id' => $rating_scale_id,
                                'type' => 1,
                                'time' => time()
                            ];
                        }
                    }
                    unset($param['rating_scale_front']);
                    break;
                case 2:
                    if (!empty($param['rating_scale_after'])) {
                        foreach ($param['rating_scale_after'] as $rating_scale_id) {
                            $ratingScaleData[] = [
                                'rating_scale_id' => $rating_scale_id,
                                'type' => 2,
                                'time' => time()
                            ];
                        }
                    }
                    unset($param['rating_scale_after']);
                    break;
                case 3:
                    if (!empty($param['rating_scale_front'])) {
                        foreach ($param['rating_scale_front'] as $rating_scale_id) {
                            $ratingScaleData[] = [
                                'rating_scale_id' => $rating_scale_id,
                                'type' => 1,
                                'time' => time()
                            ];
                        }
                    }
                    if (!empty($param['rating_scale_after'])) {
                        foreach ($param['rating_scale_after'] as $rating_scale_id) {
                            $ratingScaleData[] = [
                                'rating_scale_id' => $rating_scale_id,
                                'type' => 2,
                                'time' => time()
                            ];
                        }
                    }
                    unset($param['rating_scale_front']);
                    unset($param['rating_scale_after']);
                    break;
            }
            $param['unit_id'] = $this->userData['unit_id'];
            $param['uid'] = $this->userData['id'];
            $param['time'] = time();
            $task_id = $TrainingTaskModel->insertGetId($param);
            if (!empty($departmentData)) {
                foreach ($departmentData as &$department) {
                    $department['task_id'] = $task_id;
                }
                $TrainingTaskDepartmentModel = new TrainingTaskDepartmentModel();
                $TrainingTaskDepartmentModel->insertAll($departmentData);
            }
            if (!empty($ratingScaleData)) {
                foreach ($ratingScaleData as &$ratingScale) {
                    $ratingScale['task_id'] = $task_id;
                }
                $TrainingTaskRatingScaleModel = new TrainingTaskRatingScaleModel();
                $TrainingTaskRatingScaleModel->insertAll($ratingScaleData);
            }
            $info->save([
                'is_del' => 1,
                'del_time' => time()
            ]);
            $TrainingTaskModel->commit();
            return success();
        } catch (\Exception $e) {
            $TrainingTaskModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 编辑发布记录
     * @return bool|string
     */
    public function update(): bool|string
    {
        $TrainingTaskModel = new TrainingTaskModel();
        $TrainingTaskModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'name|讲座名称' => 'require',
                'type_id|讲座类型' => 'require',
                'start_time|举行开始时间' => 'require',
                'end_time|举行结束时间' => 'require',
                'review|报告是否需要审核' => 'require',
                'address|举行地址' => 'require',
                'lecturer_id|讲师' => 'require',
                'textbook_id|教材' => 'require',
                'is_download|是否允许下载' => 'require',
                'task_type|附带任务类型' => 'require',
                'result_read_auth|结果查看权限' => 'require',
                'introduce|简介' => 'require',
                'department|参与部门' => 'require'
            ]);
            $info = $TrainingTaskModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $TrainingTaskDepartmentModel = new TrainingTaskDepartmentModel();
            $TrainingTaskRatingScaleModel = new TrainingTaskRatingScaleModel();

            if (!empty($param['department_del'])){
                $TrainingTaskDepartmentModel->where('id','in',$param['department_del'])->delete();
                unset($param['department_del']);
            }

            if (!empty($param['rating_scale_del'])) {
                $TrainingTaskRatingScaleModel->where('id','in',$param['rating_scale_del'])->delete();
                unset($param['rating_scale_del']);
            }

            if (!empty($param['department'])) {
                foreach ($param['department'] as $v) {
                    $department = [
                        'department_id' => $v['department_id']
                    ];
                    if (!empty($v['id'])){
                        $department['id'] = $v['id'];
                    }else{
                        $department['unit_id'] = $this->userData['unit_id'];
                        $department['task_id'] = $param['id'];
                        $department['time'] = time();
                    }
                    $departmentData[] = $department;
                }
                if (!empty($departmentData)) {
                    $TrainingTaskDepartmentModel->saveAll($departmentData);
                }
                unset($param['department']);
            }
            if (!empty($param['rating_scale'])){
                foreach ($param['rating_scale'] as $v) {
                    $rating_scale = [
                        'rating_scale_id' => $v['rating_scale_id'],
                        'type' => $v['type'],
                    ];
                    if (!empty($v['id'])){
                        $rating_scale['id'] = $v['id'];
                    }else{
                        $rating_scale['task_id'] = $param['id'];
                        $rating_scale['time'] = time();
                    }
                    $ratingScaleData[] = $rating_scale;
                }
                if (!empty($ratingScaleData)) {
                    $TrainingTaskRatingScaleModel->saveAll($ratingScaleData);
                }
                unset($param['rating_scale']);
            }
            $info->save($param);
            $TrainingTaskModel->commit();
            return success();
        } catch (\Exception $e) {
            $TrainingTaskModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 已发布详情
     * @return bool|string
     */
    public function details(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
            $TrainingTaskModel = new TrainingTaskModel();
            $info = $TrainingTaskModel->with([
                'typeName',
                'user',
                'TrainingLecturer',
                'TrainingTaskDepartment',
                'TrainingTaskRatingScaleFront' => function ($query) {
                    $query->with(['ratingScale']);
                },
                'TrainingTaskRatingScaleAfter' => function ($query) {
                    $query->with(['ratingScale']);
                },
                'textbook'
            ])->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            if (!empty($info['TrainingTaskDepartment'])){
                $UserService = new UserService($this->app);
                $allDepartment = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
                foreach ($info['TrainingTaskDepartment'] as &$department){
                    $department['name'] = $allDepartment[$department['department_id']]['all_name']??'--';
                }
            }
            $info['role_name'] = $info['role_name']??'超级管理员';
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 报名名单列表
     * @return bool|string
     */
    public function registrationList(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'audit_status|审核状态' => 'require|in:1,2,3',
                'pageSize|每页显示数量' => 'require'
            ]);
            $where = [];
            $where[] = ['task_id','=',$param['id']];
            $where[] = ['audit_status','=',$param['audit_status']];
            $TrainingTaskUserDelLogModel = new TrainingTaskUserDelLogModel();
            $delId = $TrainingTaskUserDelLogModel->where('uid','=',$this->userData['id'])->column('task_user_id');
            $where[] = ['id','not in',$delId];
            $TrainingTaskUserModel = new TrainingTaskUserModel();
            $query = $TrainingTaskUserModel->where($where);
            $data = $query->with([
                'user',
                'resultFront' => function ($query) {
                    $query->with(['RatingScale']);
                },
                'resultAfter' => function ($query) {
                    $query->with(['RatingScale']);
                }
            ])->paginate($param['pageSize'])->toArray();
            if (!empty($data['data'])) {
                $UserService = new UserService($this->app);
                $allDepartment = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
                foreach ($data['data'] as &$item){
                    $item['department_name'] = $allDepartment[$item['department_id']]['all_name']??'--';
                }
            }
            $data['ids'] = $query->column('id');
            if ($param['audit_status'] == 1){
                $data['count'] = $TrainingTaskUserModel->where('task_id','=',$param['id'])->count();
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 参与详情
     * @return bool|string
     */
    public function participationDetails(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
            $TrainingTaskUserModel = new TrainingTaskUserModel();
            $info = $TrainingTaskUserModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $TrainingTaskModel = new TrainingTaskModel();
            $TaskInfo = $TrainingTaskModel->with([
                'user',
                'TrainingLecturer',
                'typeName',
                'textbook',
                'TrainingTaskDepartment',
                'TrainingTaskRatingScaleFront' => function($query){
                    $query->with(['ratingScale']);
                },
                'TrainingTaskRatingScaleAfter' => function($query){
                    $query->with(['ratingScale']);
                }
            ])->find($info['task_id']);
            $TaskInfo = $TaskInfo->toArray();
            $TrainingTaskUserResultModel = new TrainingTaskUserResultModel();
            if (!empty($TaskInfo['TrainingTaskRatingScaleFront'])){
                foreach ($TaskInfo['TrainingTaskRatingScaleFront'] as &$value){
                    $value['result_id'] = $TrainingTaskUserResultModel->where([
                        ['task_user_id','=',$param['id']],
                        ['type','=',1],
                        ['rating_scale_id','=',$value['rating_scale_id']]
                    ])->value('id');
                }
            }
            if (!empty($TaskInfo['TrainingTaskRatingScaleAfter'])){
                foreach ($TaskInfo['TrainingTaskRatingScaleAfter'] as &$value){
                    $value['result_id'] = $TrainingTaskUserResultModel->where([
                        ['task_user_id','=',$param['id']],
                        ['type','=',2],
                        ['rating_scale_id','=',$value['rating_scale_id']]
                    ])->value('id');
                }
            }
            if (!empty($TaskInfo['TrainingTaskDepartment'])){
                $UserService = new UserService($this->app);
                $allDepartment = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
                foreach ($TaskInfo['TrainingTaskDepartment'] as &$department){
                    $department['name'] = $allDepartment[$department['department_id']]['all_name']??'--';
                }
            }
            return success([
                'info' => $info,
                'TaskInfo' => $TaskInfo
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 删除参与记录
     * @return bool|string
     */
    public function logDel(): bool|string
    {

        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
            $TrainingTaskUserDelLogModel = new TrainingTaskUserDelLogModel();
            if (is_array($param['id'])){
                foreach ($param['id'] as $id){
                    $saveData[] = [
                        'uid' => $this->userData['id'],
                        'task_user_id' => $id,
                        'time' => time()
                    ];
                }
                if (!empty($saveData)){
                    $TrainingTaskUserDelLogModel->insertAll($saveData);
                }
            }else{
                $TrainingTaskUserDelLogModel->insert([
                    'uid' => $this->userData['id'],
                    'task_user_id' => $param['id'],
                    'time' => time()
                ]);
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 审核报名
     * @return bool|string
     */
    public function audit(): bool|string
    {
        $TrainingTaskUserModel = new TrainingTaskUserModel();
        $TrainingTaskUserModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'audit_status|状态' => 'require|in:2,3'
            ]);
            $TrainingTaskUserModel->where('id', 'in', $param['id'])->update([
                'audit_status' => $param['audit_status'],
                'audit_time' => time()
            ]);
            $task_id = $TrainingTaskUserModel->where('id', 'in', $param['id'])->value('task_id');
            if ($param['audit_status'] == 2) {
                $TrainingTaskModel = new TrainingTaskModel();
                $taskInfo = $TrainingTaskModel->find($task_id);
                //自增报名人数
                $taskInfo->inc('review_num', count($param['id']))->save();
                //每个部门人数统计增加
                $user = $TrainingTaskUserModel->field('id,uid')->where('id', 'in', $param['id'])->with([
                    'user'
                ])->select()->toArray();
                $DepartmentData = [];
                foreach ($user as $v){
                    if (isset($DepartmentData[$v['department_id']])){
                        $DepartmentData[$v['department_id']]++;
                    }else{
                        $DepartmentData[$v['department_id']] = 1;
                    }
                }
                $TrainingTaskDepartmentModel = new TrainingTaskDepartmentModel();
                foreach ($DepartmentData as $k=>$v){
                    $TrainingTaskDepartmentModel->where([
                        ['task_id','=',$task_id],
                        ['department_id','=',$k]
                    ])->inc('user_num',$v)->save();
                }
            }
            $TrainingTaskUserModel->commit();
            return success();
        } catch (\Exception $e) {
            $TrainingTaskUserModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 请假详情
     * @return bool|string
     */
    public function leaveInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $TrainingTaskUserModel = new TrainingTaskUserModel();
            $info = $TrainingTaskUserModel->with(['user'])->find($param['id']);
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 审核请假
     * @return bool|string
     */
    public function auditLeave(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'leave_status|状态' => 'require|in:2,3'
            ]);
            $TrainingTaskUserModel = new TrainingTaskUserModel();
            $info = $TrainingTaskUserModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $update['leave_status'] = $param['leave_status'];
            if ($param['leave_status'] == 2) {
                $update['status'] = 5;
            }
            $info->save($update);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 结束讲座
     * @return bool|string
     */
    public function end(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
            $TrainingTaskModel = new TrainingTaskModel();
            $info = $TrainingTaskModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info->save([
                'status' => 3
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 导出报名待审核名单
     * @return bool|string
     */
    public function auditExport(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $TrainingTaskUserModel = new TrainingTaskUserModel();
            $data = $TrainingTaskUserModel->where('id','in',$param['id'])->with(['user'])->select()->toArray();
            // 创建新的Spreadsheet对象
            $spreadsheet = new Spreadsheet();
            // 获取活动的工作表
            $sheet = $spreadsheet->getActiveSheet();
            // 设置工作表标题
            $sheet->setTitle('待审核');
            // 设置单元格数据
            $sheet->setCellValue('A1', '名称');
            $sheet->setCellValue('B1', '联系方式');
            $sheet->setCellValue('C1', '性别');
            $sheet->setCellValue('D1', '年龄');
            $sheet->setCellValue('E1', '身份证号');
            $sheet->setCellValue('F1', '注册账号');
            $sheet->setCellValue('G1', '所在部门');
            $sheet->setCellValue('H1', '学籍状态');
            $sheet->setCellValue('I1', '审核情况');
            $sheet->setCellValue('J1', '前置任务完成情况');
            $sheet->setCellValue('K1', '报名时间');
            if (count($data) > 0) {
                $key = 2;
                $UserService = new UserService($this->app);
                $DelDepartment = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
                foreach ($data as $item) {
                    //学籍状态
                    $student_name = match ($item['student_status']) {
                        0 => '不限',
                        1 => '在读',
                        2 => '已毕业',
                        3 => '已退学',
                        4 => '休学',
                        default => '--',
                    };
                    if ($item['is_finish_front'] == 1){
                        $is_finish = '已完成';
                    }else{
                        $is_finish = '未完成';
                    }
                    // 设置单元格数据
                    $sheet->setCellValue('A'.$key, $item['user_name']??'--');
                    $sheet->setCellValue('B'.$key, $item['phone']??'--');
                    $sheet->getStyle('B'.$key)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                    $sheet->setCellValue('C'.$key, $item['sex'] == 1 ? '男' : '女');
                    $sheet->setCellValue('D'.$key, $item['age']?:'--');
                    $sheet->setCellValue('E'.$key, $item['id_card']?:'--');
                    $sheet->getStyle('E'.$key)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                    $sheet->setCellValue('F'.$key, $item['username']?:'--');
                    $sheet->setCellValue('G'.$key, $DelDepartment[$item['department_id']]['all_name']??'--');
                    $sheet->setCellValue('H'.$key, $student_name);
                    $sheet->setCellValue('I'.$key, '待审核');
                    $sheet->setCellValue('J'.$key, $is_finish);
                    $sheet->setCellValue('K'.$key, date('Y-m-d H:i:s', $item['time']));
                    $key++;
                }
            }
            $writer = new Xlsx($spreadsheet);
            $ext = '.xlsx';
            $save_name = '/export/training'.date('Ym').'/'.date('d').'_'.time().uniqid();
            $file_path  = dirname('./public' . $save_name.$ext);
            folder_build($file_path);
            $writer->save('./public' . $save_name . $ext);
            return success(oss('./public' . $save_name . $ext, $ext));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 导出报名已允许名单
     * @return bool|string
     */
    public function auditExport2(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $TrainingTaskUserModel = new TrainingTaskUserModel();
            $data = $TrainingTaskUserModel->where('id','in',$param['id'])->with(['user'])->select()->toArray();

            // 创建新的Spreadsheet对象
            $spreadsheet = new Spreadsheet();
            // 获取活动的工作表
            $sheet = $spreadsheet->getActiveSheet();
            // 设置工作表标题
            $sheet->setTitle('已允许');
            // 设置单元格数据
            $sheet->setCellValue('A1', '名称');
            $sheet->setCellValue('B1', '联系方式');
            $sheet->setCellValue('C1', '性别');
            $sheet->setCellValue('D1', '年龄');
            $sheet->setCellValue('E1', '身份证号');
            $sheet->setCellValue('F1', '注册账号');
            $sheet->setCellValue('G1', '所在部门');
            $sheet->setCellValue('H1', '学籍状态');
            $sheet->setCellValue('I1', '可否正常参与活动');
            $sheet->setCellValue('J1', '审核情况');
            $sheet->setCellValue('K1', '前置任务完成情况');
            $sheet->setCellValue('L1', '报名时间');
            if (count($data) > 0) {
                $key = 2;
                $UserService = new UserService($this->app);
                $DelDepartment = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
                foreach ($data as $item) {
                    //学籍状态
                    $student_name = match ($item['student_status']) {
                        0 => '不限',
                        1 => '在读',
                        2 => '已毕业',
                        3 => '已退学',
                        4 => '休学',
                        default => '--',
                    };
                    if ($item['is_finish_front'] == 1){
                        $is_finish = '已完成';
                    }else{
                        $is_finish = '未完成';
                    }
                    // 设置单元格数据
                    $sheet->setCellValue('A'.$key, $item['user_name']??'--');
                    $sheet->setCellValue('B'.$key, $item['phone']??'--');
                    $sheet->getStyle('B'.$key)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                    $sheet->setCellValue('C'.$key, $item['sex'] == 1 ? '男' : '女');
                    $sheet->setCellValue('D'.$key, $item['age']?:'--');
                    $sheet->setCellValue('E'.$key, $item['id_card']?:'--');
                    $sheet->getStyle('E'.$key)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                    $sheet->setCellValue('F'.$key, $item['username']?:'--');
                    $sheet->setCellValue('G'.$key, $DelDepartment[$item['department_id']]['all_name']??'--');
                    $sheet->setCellValue('H'.$key, $student_name);
                    $sheet->setCellValue('I'.$key, $item['leave_status']?'有请假':'正常赴约');
                    $sheet->setCellValue('J'.$key, '已允许');
                    $sheet->setCellValue('K'.$key, $is_finish);
                    $sheet->setCellValue('L'.$key, date('Y-m-d H:i:s', $item['time']));
                    $key++;
                }
            }
            $writer = new Xlsx($spreadsheet);
            $ext = '.xlsx';
            $save_name = '/export/training'.date('Ym').'/'.date('d').'_'.time().uniqid();
            $file_path  = dirname('./public' . $save_name.$ext);
            folder_build($file_path);
            $writer->save('./public' . $save_name . $ext);
            return success(oss('./public' . $save_name . $ext, $ext));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 导出报名已拒绝名单
     * @return bool|string
     */
    public function auditExport3(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $TrainingTaskUserModel = new TrainingTaskUserModel();
            $data = $TrainingTaskUserModel->where('id','in',$param['id'])->with(['user'])->select()->toArray();

            // 创建新的Spreadsheet对象
            $spreadsheet = new Spreadsheet();
            // 获取活动的工作表
            $sheet = $spreadsheet->getActiveSheet();
            // 设置工作表标题
            $sheet->setTitle('待审核');
            // 设置单元格数据
            $sheet->setCellValue('A1', '名称');
            $sheet->setCellValue('B1', '联系方式');
            $sheet->setCellValue('C1', '性别');
            $sheet->setCellValue('D1', '年龄');
            $sheet->setCellValue('E1', '身份证号');
            $sheet->setCellValue('F1', '注册账号');
            $sheet->setCellValue('G1', '所在部门');
            $sheet->setCellValue('H1', '学籍状态');
            $sheet->setCellValue('I1', '审核情况');
            $sheet->setCellValue('J1', '前置任务完成情况');
            $sheet->setCellValue('K1', '报名时间');
            if (count($data) > 0) {
                $key = 2;
                $UserService = new UserService($this->app);
                $DelDepartment = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
                foreach ($data as $item) {
                    //学籍状态
                    $student_name = match ($item['student_status']) {
                        0 => '不限',
                        1 => '在读',
                        2 => '已毕业',
                        3 => '已退学',
                        4 => '休学',
                        default => '--',
                    };
                    if ($item['is_finish_front'] == 1){
                        $is_finish = '已完成';
                    }else{
                        $is_finish = '未完成';
                    }
                    // 设置单元格数据
                    $sheet->setCellValue('A'.$key, $item['user_name']??'--');
                    $sheet->setCellValue('B'.$key, $item['phone']??'--');
                    $sheet->getStyle('B'.$key)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                    $sheet->setCellValue('C'.$key, $item['sex'] == 1 ? '男' : '女');
                    $sheet->setCellValue('D'.$key, $item['age']?:'--');
                    $sheet->setCellValue('E'.$key, $item['id_card']?:'--');
                    $sheet->getStyle('E'.$key)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                    $sheet->setCellValue('F'.$key, $item['username']?:'--');
                    $sheet->setCellValue('G'.$key, $DelDepartment[$item['department_id']]['all_name']??'--');
                    $sheet->setCellValue('H'.$key, $student_name);
                    $sheet->setCellValue('I'.$key, '已拒绝');
                    $sheet->setCellValue('J'.$key, $is_finish);
                    $sheet->setCellValue('K'.$key, date('Y-m-d H:i:s', $item['time']));
                    $key++;
                }
            }
            $writer = new Xlsx($spreadsheet);
            $ext = '.xlsx';
            $save_name = '/export/training'.date('Ym').'/'.date('d').'_'.time().uniqid();
            $file_path  = dirname('./public' . $save_name.$ext);
            folder_build($file_path);
            $writer->save('./public' . $save_name . $ext);
            return success(oss('./public' . $save_name . $ext, $ext));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 参与用户
     * @return bool|string
     */
    public function participatingUsers(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
            $where[] = ['task_id','=',$param['id']];
            $where[] = ['audit_status','=',2];
            $TrainingTaskUserDelLogModel = new TrainingTaskUserDelLogModel();
            $delId = $TrainingTaskUserDelLogModel->where('uid','=',$this->userData['id'])->column('task_user_id');
            $where[] = ['id','not in',$delId];
            $TrainingTaskUserModel = new TrainingTaskUserModel();
            $query = $TrainingTaskUserModel->where($where);
            $data = $query->with([
                'user',
            ])->select()->toArray();
            if (!empty($data)) {
                $UserService = new UserService($this->app);
                $allDepartment = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
                foreach ($data as &$item){
                    $item['department_name'] = $allDepartment[$item['department_id']]['all_name']??'--';
                }
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

}